(ns acst.handler
  (:use

        [compojure.core :only [routes]]
        [hiccup.middleware :only [wrap-base-url]]
        [noir.validation :only [wrap-noir-validation]]
        [noir.cookies :only [wrap-noir-cookies]]

        )
  (:require [compojure.core :refer [defroutes routes GET]]
            [compojure.route :as route]
            [compojure.handler]
            [noir.util.middleware :refer [wrap-request-map]]
            [ring.middleware.defaults :refer [site-defaults wrap-defaults]]
            [ring.logger :refer [wrap-with-logger]]
            [ring.middleware.anti-forgery :as af]
            [ring.middleware.json :refer [wrap-json-response wrap-json-body wrap-json-params]]
            [ring.middleware.format :refer [wrap-restful-format]]
            [ring.middleware.session.memory :refer [memory-store]]
            [noir.validation :refer [wrap-noir-validation]]
            [noir.cookies :refer [wrap-noir-cookies]]
            [noir.session :refer [clear! mem wrap-noir-session wrap-noir-flash]]
            ;[acst.routes.home :refer [home-routes]]
            [acst.routes.auth :refer [auth-routes]]
            [acst.routes.index :refer [index-routes]]
            [acst.routes.activities :refer [activities-routes]]
            [acst.routes.memos :refer [memos-routes]]
            [acst.routes.news :refer [news-routes]]
            [acst.routes.blog :refer [blog-routes]]
            [acst.utils.cors :refer [wrap-cors-headers]]
            [clojure.data.json :as json]))

(defn init []
  (println "acst is starting"))

(defn destroy []
  (println "acst is shutting down"))

(defroutes app-routes
           (GET "/csrf-token" [] (json/write-str {"csrf-token" af/*anti-forgery-token*}))
           (route/resources "/")
           (route/not-found "Not Found"))


(def app
  (-> (routes index-routes auth-routes activities-routes memos-routes news-routes blog-routes app-routes)
      (wrap-cors-headers
        {"Access-Control-Request-Method" "GET, POST, PUT, DELETE, OPTIONS"
         "Access-Control-Request-Headers" "X-CSRF-Token"
         "Access-Control-Allow-Origin" "*"
         "Access-Control-Allow-Credentials" "true"})
      (wrap-request-map)
      (wrap-defaults (update-in (dissoc site-defaults :session) [:security] dissoc :anti-forgery))
      (wrap-noir-validation)
      (wrap-noir-cookies)
      (wrap-noir-flash)
      (wrap-noir-session
        (update-in
          (:session site-defaults)
          [:store] #(or % (memory-store mem))))
      (wrap-restful-format :formats [:json-kw])
  ;(-> (routes index-routes home-routes auth-routes app-routes)
      ;(wrap-defaults site-defaults)
      ;(wrap-noir-validation)
      ;(wrap-noir-cookies)
      ;(wrap-noir-flash)
      ;(wrap-noir-session)
      (wrap-with-logger {:printer :no-color} )
      ))

